﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using How_dude2.Resources;
using Microsoft.Phone.Tasks;
using Windows.Web.Http;
using System.Globalization;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using Newtonsoft.Json;
using How_dude2.Control;

namespace How_dude2
{
    /*http://look.superid.me/*/
    /*http://look.superid.me/js/bear.js?v=1.5*/
    public partial class MainPage : PhoneApplicationPage
    {
        private static readonly ObservableCollection<HowOldModel> howoldList = new ObservableCollection<HowOldModel>();

        public static ObservableCollection<HowOldModel> HowoldList { get { return howoldList; } }

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            lv.ItemsSource = HowoldList;
            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }

        private void Photo_Click(object sender, EventArgs e)
        {
            PhotoChooserTask task = new PhotoChooserTask();
            task.PixelHeight = 800;
            task.PixelWidth = 480;
            task.ShowCamera = true;
            task.Completed += Task_Completed;
            task.Show();
        }

        private async void Task_Completed(object sender, PhotoResult e)
        {
            if (e.Error == null && e.TaskResult == TaskResult.OK)
            {
                BitmapImage bit = new BitmapImage();
                bit.SetSource(e.ChosenPhoto);
                img.Source = bit;
                c.Children.Clear();
                howoldList.Clear();
                try
                {
                    p.IsOpen = true;

                    HttpClient http = new HttpClient();

                    http.DefaultRequestHeaders.Add("Host", "exapi.superid.me");
                    http.DefaultRequestHeaders.Add("Origin", "http://look.superid.me");
                    http.DefaultRequestHeaders.Add("Referer", "http://look.superid.me");
                    http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");

                    e.ChosenPhoto.Position = 0;

                    HttpStreamContent inputStream = new HttpStreamContent(e.ChosenPhoto.AsInputStream());
                    HttpMultipartFormDataContent mul = new HttpMultipartFormDataContent("----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    mul.Add(inputStream, "image", "test.jpg");
                    var ret = await http.PostAsync(new Uri("http://exapi.superid.me/look/pic", UriKind.Absolute), mul);
                    if (ret.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                    {
                        var text = await ret.Content.ReadAsStringAsync();
                        var model = JsonConvert.DeserializeObject<DudeResponse>(text);
                        if (model.Status.ToLower() == "success")
                        {
                            if (model.Result != null)
                            {

                                foreach (var item in model.Result.Faces)
                                {
                                    howoldList.Add(new HowOldModel
                                    {
                                        Attractive = item.Attractive,
                                        Gander = item.Sex == "male" ? "/Assets/icon-gender-male.png" : "/Assets/icon-gender-female.png",
                                        Margin = new Thickness(
                                        item.Position.Left >= 340 ? 340 : item.Position.Left,
                                        item.Position.Top >= 500 ? 500 : item.Position.Top,
                                        10,
                                        0),
                                        Des = GetDes(item.Sex, item.Attractive, model.Result.Id),
                                    });
                                }

                                foreach (var item in howoldList)
                                {
                                    var uc = new HowDudeControl { Model = item };
                                    Canvas.SetLeft(uc, item.Margin.Left);
                                    Canvas.SetTop(uc, item.Margin.Top);
                                    c.Children.Add(uc);
                                }
                            }

                        }
                    }
                    else
                    {
                        ShowMessage("服务器错误！");
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage("系统异常!");
                }
                finally
                {
                    if (howoldList.Count == 0)
                    {
                        ShowMessage();
                    }

                    p.IsOpen = false;
                }
            }
        }

        void ShowMessage(string content = "火星来的吧？")
        {
            MessageContent.Text = content + ":)";
            MessageIn.Begin();
        }

        string GetDes(string sex, int attractive, string id)
        {
            string result = "";

            if (sex == "male")
            {
                if (attractive == 0)
                {
                    result = "颜值一般般!";
                }
                else if (attractive < 25)
                {
                    result = "长成这样马云都被你吓哭了!";
                }
                else if (attractive < 50)
                {
                    result = "长成这样应该是单身狗吧？";
                }
                else if (attractive < 60)
                {
                    result = "你的颜值爆表";
                }
                else if (attractive < 90)
                {
                    result = "十个帅哥九个基";
                }
                else
                {
                    result = "这是看脸的世界";
                }
            }
            else
            {
                if (attractive == 0)
                {
                    result = "爱美的Girl的运气总不会太差";
                }
                else if (attractive < 25)
                {
                    result = "长期面瘫的你还是在家好好淘宝";
                }
                else if (attractive < 50)
                {
                    result = "一白遮百丑";
                }
                else if (attractive < 60)
                {
                    result = "你的颜值爆表!";
                }
                else if (attractive < 90)
                {
                    result = "女汉子的你";
                }
                else
                {
                    result = "靠脸就可以吃饭";
                }
            }

            if (id == "55522c1c13921930140443d5")
            {
                result = "颜值高的女孩纸，胸都不会太小。";
            }
            else if (id == "55522c2d13921930140443d6")
            {
                result = "我有病，我不止高富，我还帅";
            }
            else if (id == "example")
            {
                result = "老子长得不够帅,被人群殴";
            }

            return result;
        }

        // 用于生成本地化 ApplicationBar 的示例代码
        //private void BuildLocalizedApplicationBar()
        //{
        //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
        //    ApplicationBar = new ApplicationBar();

        //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // 使用 AppResources 中的本地化字符串创建新菜单项。
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }


    public class Position
    {
        public int Top { get; set; }
        public int Left { get; set; }
        public int Right { get; set; }
        public int Bottom { get; set; }
    }
    public class Faces
    {
        public Position Position { get; set; }
        public int Attractive { get; set; }
        public string Sex { get; set; }
    }
    public class Result
    {
        public string Image { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public List<Faces> Faces { get; set; }
        public string Id { get; set; }
    }
    public class DudeResponse
    {
        public string Status { get; set; }
        public Result Result { get; set; }
    }

    public class HowOldModel
    {
        public Thickness Margin { get; set; }

        public string Gander { get; set; }

        public int Attractive { get; set; }

        public string Des { get; set; }
    }
}